package com.rephilo.sqlSession;

import com.rephilo.pojo.MappedStatement;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class MapperProxy<T> implements InvocationHandler {

    private SqlSession sqlSession;

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //方法名
        String methodName = method.getName();
        //类的全路径名
        String className = method.getDeclaringClass().getName();

        String statementId = className + "." + methodName;


        MappedStatement statement = sqlSession.getConfiguration().getMappedStatementMap().get(statementId);
        if (statement != null) {
            String sqlType = statement.getSqlType();
            //返回值类型是否做了泛型类型参数化（是否返回值有泛型）
            switch (sqlType) {
                case "insert":
                    return sqlSession.insert(statementId, args);
                case "update":
                    return sqlSession.update(statementId, args);
                case "delete":
                    return sqlSession.delete(statementId, args);
                case "select":
                    Type returnType = method.getGenericReturnType();
                    if (returnType instanceof ParameterizedType) {
                        return sqlSession.selectList(statementId, args);
                    }

                    return sqlSession.selectOne(statementId, args);
            }
        }

        return null;
    }

    public MapperProxy(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }
}
